<template>
  <div class="app-container">
    <div>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:deviceType:add']">新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" style="display:none" />
      </el-row>

      <el-table v-loading="loading" :data="typeList">
      <el-table-column label="编码" align="center" prop="code" />
      <el-table-column label="分类" align="center" prop="category" />
      <el-table-column label="设备类型" align="center" prop="name" />
      <el-table-column label="是否启用" align="center" prop="enabled">
        <template slot-scope="scope">
          <div style="display:inline-flex;align-items:center;">
            <el-switch
              v-model="scope.row.enabled"
              :active-value="1"
              :inactive-value="0"
              @change="onToggleEnabled(scope.row,$event)"
            />
            <span style="margin-left:8px;color:#303133;">{{ scope.row.enabled===1?'启用':'禁用' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:deviceType:edit']">编辑</el-button>
          <el-button
            size="mini" type="text" icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:deviceType:remove']"
            style="color: #f56c6c;"
          >删除</el-button>
        </template>
      </el-table-column>
      </el-table>
    </div>
    <!-- 弹窗：新增/编辑设备类型 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="520px" append-to-body :close-on-click-modal="false" :show-close="false">
      <device-type-form
        v-if="dialogVisible"
        :mode="dialogMode"
        :code="editCode"
        :disable-enabled="false"
        @success="onFormSuccess"
        @close="dialogVisible=false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listDeviceType, delDeviceType, updateDeviceType } from "@/api/dict/deviceType"
import DeviceTypeForm from './components/DeviceTypeForm.vue'
import { refreshDictionary } from '@/utils/dictionary'

export default {
  name: "DeviceType",
  components: { DeviceTypeForm },
  computed: {},
  data() {
    return {
      loading: true,
      showSearch: false,
      total: 0,
      typeList: [],
      queryParams: { pageNum: 1, pageSize: 10 },
      dialogVisible:false,
      dialogMode:'create',
      editCode:'',
      currentEditingInUse: false,
      dialogTitle:'',
    }
  },
  async created() { await this.getList() },
  watch:{},
  methods: {
    async getList() {
      this.loading = true
      const res = await listDeviceType(this.queryParams)
      this.typeList = (res.rows || []).map(it => ({
        ...it,
        enabled: (it.enabled===undefined||it.enabled===null) ? 1 : ((it.enabled===1||it.enabled==='1'||it.enabled===true)?1:0)
      }))
      this.total = res.total
      this.loading = false
    },
    handleAdd(){ this.dialogMode='create'; this.editCode='';  this.dialogVisible=true },
    handleUpdate(row){
      this.dialogMode='edit';
      this.editCode=row.code;
      this.dialogVisible=true
    },
    handleDelete(row) {
      const code = row.code;
      this.$modal.confirm('是否确认删除设备类型编号为"'+code+'"的数据项？')
        .then(()=> delDeviceType(code))
        .then(()=>{ this.getList(); this.$modal.msgSuccess("删除成功") })
        .catch(err=>{ if (err && err.response && err.response.data && err.response.data.msg) { this.$modal.msgError({ message: err.response.data.msg, duration: 2000 }) } })
    },
    onFormSuccess(){ this.dialogVisible=false; this.getList() },
    async onToggleEnabled(row, newVal){
      const original = row.enabled
      row.enabled = newVal
      try {
        await updateDeviceType({ code: row.code, enabled: Number(newVal) })
        this.$modal.msgSuccess({ message: '状态已更新', duration: 800 })
        // 刷新字典缓存，确保其他页面使用最新的数据
        await refreshDictionary('equipmentTypes')
      } catch (error) {
        row.enabled = original
        // 显示后端返回的具体错误信息
        const errorMsg = error.response?.data?.msg || '更新失败'
        this.$modal.msgError({ message: errorMsg, duration: 2000 })
      }
    }
  }
}
</script>


